<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="竞赛编码" prop="competitionCoding">
        <el-input
            v-model="queryParams.competitionCoding"
            placeholder="请输入竞赛编码"
            clearable
        />
      </el-form-item>
      <el-form-item label="竞赛名称" prop="competitionName">
        <el-input
            v-model="queryParams.competitionName"
            placeholder="请输入竞赛名称"
            clearable
        />
      </el-form-item>
      <el-form-item label="竞赛目录" prop="competitionCatalog">
        <el-select v-model="queryParams.competitionCatalog" placeholder="请选择竞赛目录" clearable
                   style="width: 100px;">
          <el-option
              v-for="dict in sys_competition_catalog"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="获奖级别" prop="awardLevel">
        <el-select v-model="queryParams.awardLevel" placeholder="请选择获奖级别" clearable style="width: 100px;">
          <el-option
              v-for="dict in sys_award_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="获奖等级" prop="awardRank">
        <el-select v-model="queryParams.awardRank" placeholder="请选择获奖等级" clearable style="width: 100px;">
          <el-option
              v-for="dict in sys_award_rank"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="指导教师" prop="instructorIds">-->
<!--        <el-select-->
<!--            v-model="queryParams.instructorIds"-->
<!--            placeholder="请选择指导教师"-->
<!--            clearable-->
<!--            style="width: 190px;"-->
<!--        >-->
<!--          <el-option-->
<!--              v-for="item in instructorList"-->
<!--              :key="item.userId"-->
<!--              :label="item.nickName"-->
<!--              :value="item.userId"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="审核状态" prop="reviewStatus">
        <el-select v-model="queryParams.reviewStatus" placeholder="请选择审核状态" clearable style="width: 190px;">
          <el-option
              v-for="dict in sys_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['stuCompetition:stuCompetition:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['stuCompetition:stuCompetition:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['stuCompetition:stuCompetition:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
<!--        <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="Download"-->
<!--            @click="handleExportMain"-->
<!--            v-hasPermi="['stuCompetition:stuCompetition:export']"-->
<!--        >导出-->
<!--        </el-button>-->
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stuCompetitionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="竞赛编码" align="center" prop="competitionCoding"/>
      <el-table-column label="竞赛名称" align="center" prop="competitionName"/>
      <el-table-column label="竞赛目录" align="center" prop="competitionCatalog">
        <template #default="scope">
          <dict-tag :options="sys_competition_catalog" :value="scope.row.competitionCatalog"/>
        </template>
      </el-table-column>
      <el-table-column label="获奖级别" align="center" prop="awardLevel">
        <template #default="scope">
          <dict-tag :options="sys_award_level" :value="scope.row.awardLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="获奖等级" align="center" prop="awardRank">
        <template #default="scope">
          <dict-tag :options="sys_award_rank" :value="scope.row.awardRank"/>
        </template>
      </el-table-column>
      <!--<el-table-column label="指导教师" align="center" prop="instructorName" />-->
      <el-table-column label="指导教师" align="center" prop="instructors">
        <template #default="scope">
          <div>
      <span v-for="(instructor, index) in scope.row.instructors" :key="instructor.userId">
        {{ instructor.nickName }}<span v-if="index < scope.row.instructors.length - 1">, </span>
      </span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="获奖证书" align="center" prop="awardImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.awardImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="reviewStatus">
        <template #default="scope">
          <dict-tag :options="sys_status" :value="scope.row.reviewStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['stuCompetition:stuCompetition:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['stuCompetition:stuCompetition:remove']">删除
          </el-button>
          <el-button link type="primary" icon="InfoFilled" @click="handleShowMembers(scope.row)">成员信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改学生竞赛对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="stuCompetitionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="竞赛编码" prop="competitionCoding">
          <el-input v-model="form.competitionCoding" placeholder="请输入竞赛编码"/>
        </el-form-item>
        <el-form-item label="竞赛名称" prop="competitionName">
          <el-input v-model="form.competitionName" placeholder="请输入竞赛名称"/>
        </el-form-item>
        <el-form-item label="竞赛目录" prop="competitionCatalog">
          <el-select v-model="form.competitionCatalog" placeholder="请选择竞赛目录">
            <el-option
                v-for="dict in sys_competition_catalog"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="获奖级别" prop="awardLevel">
          <el-select v-model="form.awardLevel" placeholder="请选择获奖级别">
            <el-option
                v-for="dict in sys_award_level"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="获奖等级" prop="awardRank">
          <el-select v-model="form.awardRank" placeholder="请选择获奖等级">
            <el-option
                v-for="dict in sys_award_rank"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指导教师" prop="instructorIds">
          <el-select multiple v-model="form.instructorIds" placeholder="请选择指导教师">
            <el-option
                v-for="item in instructorList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="获奖证书" prop="awardImg">
          <image-upload v-model="form.awardImg"/>
        </el-form-item>
<!--        <el-form-item label="审核状态" prop="reviewStatus">-->
<!--          <el-select v-model="form.reviewStatus" placeholder="请选择审核状态">-->
<!--            <el-option-->
<!--                v-for="dict in sys_status"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <el-divider content-position="center">学生竞赛成员信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddStucompetitioninfo">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteStucompetitioninfo">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="stucompetitioninfoList" :row-class-name="rowStucompetitioninfoIndex"
                  @selection-change="handleStucompetitioninfoSelectionChange" ref="stucompetitioninfo">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="姓名" prop="studentName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.studentName" placeholder="请输入姓名"/>
            </template>
          </el-table-column>
          <el-table-column label="学号" prop="studentNumber" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.studentNumber" placeholder="请输入学号"/>
            </template>
          </el-table-column>
          <el-table-column label="专业" prop="studentMajor" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.studentMajor" placeholder="请选择专业">
                <el-option
                    v-for="dict in sys_major"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="班级" prop="studentClass" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.studentClass" placeholder="请选择班级">
                <el-option
                    v-for="dict in sys_class"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="本专科" prop="undergraduateOrspecialist" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.undergraduateOrspecialist" placeholder="请选择本专科">
                <el-option
                    v-for="dict in sys_undergraduate_specialist"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <!-- <el-table-column label="导师部门" prop="deptId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.deptId" placeholder="请输入导师部门" />
            </template>
          </el-table-column> -->
          <el-table-column label="导师部门" prop="deptId" width="150">
            <template #default="scope">
              <el-tree-select v-model="scope.row.deptId" :data="deptOptions" filterable
                              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                              placeholder="请选择导师部门"
                              check-strictly @change="handleAdvisorDepartmentChange(scope.row)"/>
            </template>
          </el-table-column>
          <!-- <el-table-column label="学业导师" prop="userId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.userId" placeholder="请输入学业导师" />
            </template>
          </el-table-column> -->
          <el-table-column label="学业导师" prop="userId" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.userId" placeholder="请选择学业导师" clearable
                         @focus="handleFocus(scope.row)">
                <el-option v-for="academicAdvisor in academicAdvisorList" :key="academicAdvisor.userId"
                           :label="academicAdvisor.nickName" :value="academicAdvisor.userId"/>
              </el-select>
            </template>

            <!-- <el-input v-model="form.academicAdvisorId" placeholder="请输入学业导师" /> -->
          </el-table-column>
<!--          <el-table-column label="分值" prop="marks" width="150">-->
<!--            <template #default="scope">-->
<!--              <el-input v-model="scope.row.marks" placeholder="请输入分值"/>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--    成员信息-->
    <el-dialog title="成员信息" v-model="memberInfoOpen" width="1000px" append-to-body>
      <el-table :data="memberInfoList" border>
        <el-table-column label="序号" align="center" prop="index" width="50">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="studentName"/>
        <el-table-column label="学号" align="center" prop="studentNumber"/>
        <el-table-column label="专业" align="center" prop="studentMajor">
          <template #default="scope">
            <dict-tag :options="sys_major" :value="scope.row.studentMajor"/>
          </template>
        </el-table-column>
        <el-table-column label="班级" align="center" prop="studentClass">
          <template #default="scope">
            <dict-tag :options="sys_class" :value="scope.row.studentClass"/>
          </template>
        </el-table-column>
        <el-table-column label="本专科" align="center" prop="undergraduateOrspecialist">
          <template #default="scope">
            <dict-tag :options="sys_undergraduate_specialist" :value="scope.row.undergraduateOrspecialist"/>
          </template>
        </el-table-column>
        <el-table-column label="导师部门" align="center" prop="deptName"/>
        <el-table-column label="学业导师" align="center" prop="nickName"/>
        <el-table-column label="分值" align="center" prop="marks"/>
        <el-table-column label="备注" align="center" prop="remark"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="StuCompetition">
import {
  listStuCompetition,
  getStuCompetition,
  delStuCompetition,
  addStuCompetition,
  updateStuCompetition
} from "@/api/stuCompetition/stuCompetition";
import {deptTreeSelect, listUser} from "@/api/system/user";
import {getAdvisorList} from "@/api/student/student";
import {ElMessage} from 'element-plus'

const {proxy} = getCurrentInstance();
const {
  sys_status,
  sys_award_rank,
  sys_competition_catalog,
  sys_major,
  sys_class,
  sys_undergraduate_specialist,
  sys_award_level
} = proxy.useDict('sys_status', 'sys_award_rank', 'sys_competition_catalog', 'sys_major', 'sys_class', 'sys_undergraduate_specialist', 'sys_award_level');

const stuCompetitionList = ref([]);
const stucompetitioninfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedStucompetitioninfo = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const instructorList = ref([]); //指导教师列表

// 成员信息的响应式变量
const memberInfoOpen = ref(false);
const memberInfoList = ref([]);
const deptOptions = ref(undefined); //导师部门列表
const academicAdvisorList = ref(undefined); //学业导师列表
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    competitionCoding: null,
    competitionName: null,
    competitionCatalog: null,
    awardLevel: null,
    awardRank: null,
    instructorIds: [],
    reviewStatus: null,
  },
  rules: {
    competitionCoding: [
      {required: true, message: "竞赛编码不能为空", trigger: "blur"}
    ],
    competitionName: [
      {required: true, message: "竞赛名称不能为空", trigger: "blur"}
    ],
    competitionCatalog: [
      {required: true, message: "竞赛目录不能为空", trigger: "change"}
    ],
    awardLevel: [
      {required: true, message: "获奖级别不能为空", trigger: "change"}
    ],
    awardRank: [
      {required: true, message: "获奖等级不能为空", trigger: "change"}
    ],
    instructorIds: [
      {required: true, message: "指导教师不能为空", trigger: "blur"}
    ],
    /*    awardImg: [
          { required: true, message: "获奖证书不能为空", trigger: "blur" }
        ],*/
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询学生竞赛列表 */
function getList() {
  loadinstructorList(); //获取指导教师列表instructorList
  loading.value = true;
  listStuCompetition(queryParams.value).then(response => {
    stuCompetitionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//获取指导教师列表instructorList
function loadinstructorList() {
  listUser().then(response => {
    instructorList.value = response.rows;
    academicAdvisorList.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 成员信息按钮操作 */
function handleShowMembers(row) {
  const _id = row.id;
  getStuCompetition(_id).then(response => {
    // 从返回的详细信息中提取成员信息
    memberInfoList.value = response.data.stucompetitioninfoList || [];
    // 打开成员信息对话框
    memberInfoOpen.value = true;
  });
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    competitionCoding: null,
    competitionName: null,
    competitionCatalog: null,
    awardLevel: null,
    awardRank: null,
    instructorIds: null,
    awardImg: null,
    reviewStatus: null,
    remark: null,
    userId: null,
    deptId: null,
  };
  stucompetitioninfoList.value = [];
  proxy.resetForm("stuCompetitionRef");
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生竞赛";
  loadinstructorList()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStuCompetition(_id).then(response => {
    form.value = response.data;
    stucompetitioninfoList.value = response.data.stucompetitioninfoList;
    open.value = true;
    title.value = "修改学生竞赛";
  });
  getDeptTree();
  loadinstructorList();
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stuCompetitionRef"].validate(valid => {
    if (valid) {
      form.value.stucompetitioninfoList = stucompetitioninfoList.value;
      if (form.value.id != null) {
        updateStuCompetition(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStuCompetition(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除学生竞赛编号为"' + _ids + '"的数据项？').then(function () {
    return delStuCompetition(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 学生竞赛个人信息序号 */
function rowStucompetitioninfoIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 学生竞赛个人信息添加按钮操作 */
function handleAddStucompetitioninfo() {
  let obj = {};
  obj.studentName = "";
  obj.studentNumber = "";
  obj.studentMajor = "";
  obj.studentClass = "";
  obj.undergraduateOrspecialist = "";
  obj.userId = "";
  obj.deptId = "";
  obj.marks = "";
  obj.remark = "";
  getDeptTree();
  stucompetitioninfoList.value.push(obj);
}

/** 学生竞赛个人信息删除按钮操作 */
function handleDeleteStucompetitioninfo() {
  if (checkedStucompetitioninfo.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的学生竞赛个人信息数据");
  } else {
    const stucompetitioninfos = stucompetitioninfoList.value;
    const checkedStucompetitioninfos = checkedStucompetitioninfo.value;
    stucompetitioninfoList.value = stucompetitioninfos.filter(function (item) {
      return checkedStucompetitioninfos.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleStucompetitioninfoSelectionChange(selection) {
  checkedStucompetitioninfo.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExportMain() {
  proxy.download('stuCompetition/stuCompetition/export', {
    ...queryParams.value
  }, `竞赛信息_${new Date().getTime()}.xlsx`)
}

/**学业导师部门修改 */
const handleAdvisorDepartmentChange = (val) => {
  val.userId = null
  // console.log(val);
  // form.value.deptId = val;
  // form.value.userId = null;
}

//获取学业导师列表
function loadAdvisorList(deptId) {
  getAdvisorList(deptId).then(response => {
    academicAdvisorList.value = response;
    console.log(academicAdvisorList.value);

  });
}

const handleFocus = (val) => {
  if (val.deptId) {
    loadAdvisorList(val.deptId)
  } else {
    ElMessage({
      message: '请先选择部门',
      type: 'error'
    });
  }
}

getList();
</script>
